import json
import random

from django.core.cache import cache
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20190711 import sms_client, models


def verification_code():
    code = random.randint(100000, 999999)
    return code


def sms_code(phone):
    try:
        #cred = credential.Credential("AKIDZt63gKJVtqnqsfqgsnbHeohO2Thm8wKT", "YNFvLp79vTEftszzb2EbjHZntnRq44qR")
        cred = credential.Credential("AKIDmJccLoI8tOdbIkPvdCZibGk12uXxjUaX", "ua1B5jAMRM0OWP1TfaIqEPM3YgYDclfI")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "sms.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "", clientProfile)
        code = verification_code()
        print(code)
        phones = "+86"+phone
        req = models.SendSmsRequest()
        params = {
            "PhoneNumberSet": [phones],
            "TemplateID": "520531",
            "SmsSdkAppid": "1400303888",
            "TemplateParamSet": [str(code), "2"],
            "Sign": "禄荃网络科技"
        }
        req.from_json_string(json.dumps(params))

        resp = client.SendSms(req)
        print(resp.to_json_string())
        cache.set(phone, code, 60 * 5)

    except TencentCloudSDKException as err:
        print(err)

# if __name__ == '__main__':
#     sms_code('17786648013')